package com.wenda.lucene;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.factory.annotation.Value;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.wenda.bean.ThesisBean;
import com.wenda.entity.Thesis;
import com.wenda.util.DateUtil;
import com.wenda.util.ElementDict;
import com.wenda.util.TextCosine;

/**
 * 论题索引类
 * @author Administrator
 */

public class ThesisIndex {
	@Value("${LUCENE_INDEX_DIRECTORY}")
	private String LUCENE_INDEX_DIRECTORY;
	
	private Directory dir= null;

	/**
	 * 获取IndexWriter实例
	 * @return
	 * @throws Exception
	 */
	private IndexWriter getWriter()throws Exception{
		dir=FSDirectory.open(Paths.get(LUCENE_INDEX_DIRECTORY));
		IKAnalyzer analyzer=new IKAnalyzer();
		IndexWriterConfig iwc=new IndexWriterConfig(analyzer);
		IndexWriter writer=new IndexWriter(dir, iwc);
		return writer;
	}
	
	/**
	 * 添加论文索引
	 * @param thesis
	 */
	public void addIndex(Thesis thesis)throws Exception{
		//thesisId  thesisname thesiscontent  
		//thesisstatus  createId  createdate
		//updatedate  checktype  checkname  checkdate   specialtyId  
		IndexWriter writer=getWriter();
		Document doc=new Document();
		doc.add(new StringField("thesisId",String.valueOf(thesis.getThesisId()),Field.Store.YES));
		doc.add(new StringField("collegeId",String.valueOf(thesis.getCollegeId()),Field.Store.YES));
		doc.add(new TextField("thesisName",thesis.getThesisName(),Field.Store.YES));
		doc.add(new StringField("createDate",DateUtil.formatDate(thesis.getCreateDate(), "yyyy"),Field.Store.YES));
		writer.addDocument(doc);
		writer.close();
	}
	
	/**
	 * 更新论文索引
	 * @param thesis
	 * @throws Exception
	 */
	public void updateIndex(Thesis thesis)throws Exception{
		IndexWriter writer=getWriter();
		Document doc=new Document();
		doc.add(new StringField("thesisId",String.valueOf(thesis.getThesisId()),Field.Store.YES));
		doc.add(new StringField("collegeId",String.valueOf(thesis.getCollegeId()),Field.Store.YES));
		doc.add(new TextField("thesisName",thesis.getThesisName(),Field.Store.YES));
		doc.add(new StringField("createDate",DateUtil.formatDate(thesis.getCreateDate(), "yyyy"),Field.Store.YES));
		writer.updateDocument(new Term("thesisId", String.valueOf(thesis.getThesisId())), doc);
		writer.close();
	}
	
	/**
	 * 删除指定论题的索引
	 * @param thesisId
	 * @throws Exception
	 */
	public void deleteIndex(String thesisId)throws Exception{
		IndexWriter writer = getWriter();
		writer.deleteDocuments(new Term("thesisId",thesisId));
		writer.forceMergeDeletes(); // 强制删除
		writer.commit();
		writer.close();
	}
	/**
	 * 查询论题信息
	 * @param str
	 * @return
	 * @throws Exception 
	 */
	public List<ThesisBean> searchThesis(String str) throws Exception {
		List<ThesisBean> results = new ArrayList<>();
		// 确定索引库
		dir = FSDirectory.open(Paths.get(LUCENE_INDEX_DIRECTORY));
		IndexReader reader = DirectoryReader.open(dir);
		// 建立搜索索引
		IndexSearcher searcher = new IndexSearcher(reader);
		// 设置分词器
		Analyzer analyzer = new IKAnalyzer();
		//根据论题名称查询相似论题
		QueryParser queryParser = new QueryParser("thesisName", analyzer);
		Query query = queryParser.parse(str);
		TopDocs hits = searcher.search(query, 100);
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document doc = searcher.doc(scoreDoc.doc);
			String title = doc.get("thesisName");
			double score = docsLike(str,title);
			ThesisBean thesis = new ThesisBean();
			thesis.setThesisId(Integer.valueOf(doc.get("thesisId")));
			thesis.setCollegeId(Integer.valueOf(doc.get("collegeId")));
			thesis.setThesisName(doc.get("thesisName"));
			thesis.setCreateDate(DateUtil.formatString(doc.get("createDate"), "yyyy"));
			thesis.setScore(score);
			results.add(thesis);
		}
		reader.close();
		return results;
	}
	/**
	 * 
	 * @param str
	 * @return 返回值：1： 可以，-1：不可用，0：待审核
	 * @throws Exception
	 */
	public int likeThesis(String str) throws Exception {
		// 确定索引库
		dir = FSDirectory.open(Paths.get(LUCENE_INDEX_DIRECTORY));
		IndexReader reader = DirectoryReader.open(dir);
		// 建立搜索索引
		IndexSearcher searcher = new IndexSearcher(reader);
		// 设置分词器
		Analyzer analyzer = new IKAnalyzer();
		//根据论题名称查询相似论题
		QueryParser queryParser = new QueryParser("thesisName", analyzer);
		Query query = queryParser.parse(str);
		TopDocs hits = searcher.search(query, 10);
		double max = 0;
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document doc = searcher.doc(scoreDoc.doc);
			String title = doc.get("thesisName");
			double score = docsLike(str,title);
			if(score > max) {
				max = score;
			}
		}
		reader.close();
		return max > 0.75 ? -1 : max > 0.5 ? 0 : 1;
	}
	
	//相似度计算
	private double docsLike(String str, String title) {
		double score = 0;
		TextCosine textCosine = new TextCosine();
		List<ElementDict> list1 = textCosine.tokenizer(str);
		List<ElementDict> list2 = textCosine.tokenizer(title);
		score = textCosine.analysis(list1, list2);
		return score;
	}	
}
